#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>
#include <pthread.h>
#include <cstdio>
#include <cstring>
using namespace std;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
class customer
{
public:
    int _ticket_num = 0;
    pthread_t _tid;
    string _name;
};

int g_ticket = 10000;

void* buyTicket(void* args)
{
    customer* cust = (customer*)args;

    while(true)
    {
        pthread_mutex_lock(&mutex);
        if(g_ticket > 0)
        {
            usleep(1000);
            cout << cust->_name << " get ticket: " << g_ticket << endl;
            g_ticket--;
            cust->_ticket_num++;
            pthread_mutex_unlock(&mutex);
        }
        else
        {
            pthread_mutex_unlock(&mutex);
            break;
        }
    }

    return nullptr;
}

int main()
{
    vector<customer> custs(5);

    for(int i = 0; i < 5; i++)
    {
        custs[i]._name= "customer-" + to_string(i + 1);
        pthread_create(&custs[i]._tid, nullptr, buyTicket, &custs[i]);
    }

    for(int i = 0; i < 5; i++)
    {
        pthread_join(custs[i]._tid, nullptr);
    }

    for(int i = 0; i < 5; i++)
    {
        cout << custs[i]._name << " get tickets: " << custs[i]._ticket_num << endl;
    }

    return 0;
}
